package com.demo.test.juc.Atomic;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author gy
 * @date 2023/7/29
 */
public class AtomicIntegerDemo {

    AtomicInteger ac = new AtomicInteger();

    void addPlus(){
        ac.getAndIncrement();
    }

    public static final int SIZE = 50;

    @Test
    public void m() throws InterruptedException {

        long startTime = System.currentTimeMillis();

        AtomicIntegerDemo atomicIntegerDemo = new AtomicIntegerDemo();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        atomicIntegerDemo.addPlus();
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
//        try { TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) { e.printStackTrace(); }

        // Causes the current thread to wait until the latch has counted down to
        //zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
        countDownLatch.await();

        System.out.println(atomicIntegerDemo.ac.get());

        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }

    @Test
    public void m3(){
        long startTime = System.currentTimeMillis();

        AtomicInteger atomicInteger = new AtomicInteger(1);
        for (int i = 0; i < 10000000; i++) {
            atomicInteger.getAndIncrement();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }
}
